package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtil;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author diva
 * @date 2025/10/7 18:16
 * @ProjectName
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFIX = "123";

    private static final Integer USER_STATUS_NORMAL = 1;
    private static final Integer USER_STATUS_UNNORMAL = 0;

    @Override
    public PageResult<UserDO> list(UserDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<UserDO> result = userMapper.selectByPage(dto);

        List<UserDO> maskedResult = result.stream().map(userDO -> {
            UserDO maskedUser = BeanUtil.copyProperties(userDO, UserDO.class);
            if (maskedUser.getPhone() != null && !maskedUser.getPhone().isEmpty()) {
                maskedUser.setPhone(DesensitizedUtil.mobilePhone(maskedUser.getPhone()));
            }
            return maskedUser;
        }).collect(Collectors.toList());

        Page<UserDO> page = (Page<UserDO>)  result;
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(maskedResult)
                .build();
    }

    @Override
    public void add(User user) {

        boolean hasNull = BeanUtil.hasNullField(user, "id","password","roleId","deptId","image","remark","updateTime","createTime");
        if(hasNull){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String rawPassword = new StringBuilder(user.getName()).append(DEFAULT_PASSWORD_SUFIX).toString();
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        userMapper.insert(user);

    }

     @Override
    public void updateById(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "id","password","roleId","deptId","image","remark","updateTime","createTime");
        if(hasNull){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }

        user.setUpdateTime(LocalDateTime.now());

        userMapper.updateById(user);
    }

    @Override
    public User getById(Integer id) {
        if (Objects.isNull(id)){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getUsersByRoleLabel(String roleLabel) {
        return userMapper.selectByRoleLabel(roleLabel);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        if(CollectionUtil.isEmpty(ids)){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        userMapper.deleteBatch(ids);
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        boolean hasNull = BeanUtil.hasNullField(userLoginDTO);
        if(hasNull){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }

        User dbuser = userMapper.selectByUsername(userLoginDTO.getUsername());

        if(Objects.isNull(dbuser)){
            CommonException.throwException(ParamEnum.Login_USERNAME_ERROR);
        }

        String userPassword = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        String encodedPassword = dbuser.getPassword();
        boolean isChecked = ObjectUtil.equals(userPassword, encodedPassword);
        if (!isChecked){
            CommonException.throwException(ParamEnum.Login_PASSWORD_ERROR);
        }
        if(Objects.equals(dbuser.getStatus(),USER_STATUS_UNNORMAL)){
            CommonException.throwException(ParamEnum.Login_USER_STATUS_ERROR);
        }

        Role role = roleMapper.selectById(dbuser.getRoleId());

        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbuser.getId());
        claims.put("username",dbuser.getUsername());

        return UserLoginVO.builder()
                .id(dbuser.getId())
                .username(dbuser.getUsername())
                .name(dbuser.getName())
                .image(dbuser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtil.generateToken(claims))
                .build();
    }
}
